#encoding:utf-8
'''
Created on March 10 2014

@author: yangluo
'''
# import pygame
import wx
import os
import socket
import threading
#import zipModule

# window_size =(420,350)
window_size =(550,380)
child_win_size = (300,200)
button_size = (70,30)

frame_color = wx.Color(255,255,255)
text_color  = wx.Color(40,139,213)


class MyFrame(wx.Frame):
    def __init__(self, parent=None,id=-1,
                   pos=wx.DefaultPosition,title='chattor_client'):
        wx.Frame.__init__(self,parent,id,title,pos,size=window_size)
        
class childFrame(wx.Frame):
    def __init__(self,image,parent=None,id=-1,
                 pos=wx.DefaultPosition,title='new'):
        temp = image.ConvertToBitmap()
        size = temp.GetWidth(), temp.GetHeight()
        wx.Frame.__init__(self, parent, id, title, pos, size)
        panel = wx.Panel(self)
        self.bmp = wx.StaticBitmap(parent=panel, bitmap=temp)
        self.SetClientSize(size)
        
class MyApp(wx.App):
    def __init__(self,port=5757,redirect=True):
        wx.App.__init__(self,redirect)
        
        self.targetDir = ''
        self.targetFile = ''
        self.targetPath = ''
        self.sendfilepath  = ''
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        #self.ip=socket.getaddrinfo(socket.gethostname(),None)[-2][4][0]
        self.ip = socket.gethostbyname(socket.gethostname())
        self.port = port
        self.conductType = ''
        self.userno = 1
        
        #create thread 
        #self.keythread_handle = threading.Thread(target=self.conductThread)
        #self.socketThread_handle = threading.Thread(target=self.socketThread)
        #self.socketThread_handle.start()
        
        self.recvThread_handle = threading.Thread(target=self.recvMsg)
        
        
    def OnInit(self):
        self.win = MyFrame()
        bkg = wx.Panel(self.win)
        bkg.SetBackgroundColour(frame_color)
        winFont = wx.Font(15,wx.MODERN,wx.NORMAL,wx.NORMAL)
        self.Bind(wx.EVT_CLOSE,self.CloseWindow)
        
        ST_ip = wx.StaticText(bkg,-1,'ip:     ')
        self.ip_text = wx.TextCtrl(bkg)
#         self.ip_text.SetEditable(True)
        self.connect_btn = wx.Button(bkg,label='connect')
        self.ip_text.SetValue(str(socket.getaddrinfo(socket.gethostname(),None)[-2][4][0]) + ':' +'5757')
        ST_ip.SetFont(winFont)
        self.ip_text.SetFont(winFont)
        self.connect_btn.SetFont(winFont)
        self.connect_btn.Bind(wx.EVT_BUTTON, self.ConnectServer)
        
        ip_hbox = wx.BoxSizer()
        ip_hbox.Add(ST_ip, proportion=1,flag=wx.ALIGN_LEFT)
        ip_hbox.Add(self.ip_text,proportion=2,flag=wx.ALIGN_LEFT)
        ip_hbox.Add(self.connect_btn,proportion=1,flag=wx.ALIGN_CENTER)
#         
#         ST_filepath = wx.StaticText(bkg,-1,"path:")
#         self.filepath = wx.TextCtrl(bkg)
#         self.browser = wx.Button(bkg,label='browser')
#         self.browser.Bind(wx.EVT_BUTTON,self.Browser)
#         ST_filepath.SetFont(winFont)
#         self.filepath.SetFont(winFont)
#         self.browser.SetFont(winFont)
#         
        self.messageList = wx.ListBox(bkg,style=wx.MULTIPLE | wx.HSCROLL,size=(300,200))
        self.messageList.SetForegroundColour(text_color)
        
        #listbox_size = (400,450)
        self.messageList.SetFont(winFont)
        listItem = ['wechat:']
        self.messageList.InsertItems(listItem,0)
        
        #self.messageList.SetSize(listbox_size)
        self.chat = wx.TextCtrl(bkg)
        self.send = wx.Button(bkg,label="send")
        self.send.Bind(wx.EVT_BUTTON, self.SendMessage)
        self.chat.SetFocus()
        self.chat.SetFont(winFont)
        self.send.SetFont(winFont)
        
#         
#         hbox1 = wx.BoxSizer()
#         hbox1.Add(ST_filepath, proportion=1)
#         hbox1.Add(self.filepath,proportion=2,border=5)
#         hbox1.Add(self.browser,proportion=1,border=5)
#         
        vbox1_2 = wx.BoxSizer(wx.VERTICAL)
        vbox1_2.Add(ip_hbox, proportion=1, flag=wx.ALIGN_CENTER,border=5)
        #vbox1_2.Add(hbox1,proportion=1,flag=wx.ALIGN_CENTER,border=5)
        
        vbox2 = wx.BoxSizer(wx.VERTICAL)
        vbox2.Add(self.messageList, proportion=0,flag=wx.EXPAND,border=5)
        
        hbox3 = wx.BoxSizer()
        hbox3.Add(self.chat,proportion=1,flag=wx.ALIGN_CENTER)
        hbox3.Add(self.send,proportion=0,flag=wx.ALIGN_CENTER)
        
        total_box = wx.BoxSizer(wx.VERTICAL)
        #total_box.Add(hbox1,proportion=1,flag=wx.ALIGN_CENTER)
        total_box.Add(vbox1_2,proportion=1,flag=wx.EXPAND|wx.ALL,border=8)
        total_box.Add(vbox2,proportion=5,flag=wx.EXPAND|wx.ALL,border=5)
        total_box.Add(hbox3,proportion=1,flag=wx.EXPAND|wx.ALL,border=8)
        bkg.SetSizer(total_box)
        
        self.win.Show()
        return True
    def CloseWindow(self,event):
        self.send('close,%d'%self.userno)
        self.sock.close()
    
    def ConnectServer(self,event):
        self.sock.close()
        self.ip = self.ip_text.GetValue().split(':')[0]
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        newSocketThread = threading.Thread(target=self.socketThread)
        newSocketThread.start()
            
    def SendMessage(self,event):
        # send the message to service so that the service 
        # spread to other clients
        newMsg = self.chat.GetValue()
        if newMsg == '':
            return
        else:
            sendMsg = 'toall,' + str(self.userno)+',' +newMsg
            self.sock.send(sendMsg)
            item = ['me:'+ newMsg]
            self.messageList.AppendItems(item)
            self.messageList.Select(self.messageList.GetCount()-1)
            self.chat.SetValue('')

    def recvMsg(self):
        # this function is used to receive the message from 
        # service all the time
        while True:
            msg = self.sock.recv(100)
            if msg.split(',')[0] == 'toall':
                from_userno = msg.split(',')[1]
                newMsg = msg.split(',')[-1]
                item = [from_userno + newMsg]
                self.messageList.AppendItems(item)
                self.messageList.Select(self.messageList.GetCount()-1)
                
    def socketThread(self): 
        self.sock.connect((self.ip,self.port))
        self.sock.send('apply,yangluo')
        msg = self.sock.recv(5)
        if msg.split(',')[0] == 'ok':
            self.userno = msg.split(',')[1]
            self.win.SetTitle('CLIENT '+str(self.userno))
            
            #start recvMsg thread here
            recvThread_handle = threading.Thread(target=self.recvMsg)
            recvThread_handle.start()
        else:
            return
                
def main():
    app = MyApp()
    app.MainLoop()

if __name__ == '__main__':
    main()






